package com.youhome.api.config;

import com.youhome.service.service.AuthenticationCompanyTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * Created by philip on 5/19/17.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurity extends WebSecurityConfigurerAdapter  {

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private AuthenticationCompanyTokenService authenticationService;

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(authenticationService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //禁用CSRF保护
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().authorizeRequests()
                //配置安全策略
                //定义请求不需要验证
                .antMatchers("/", "/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/v1/api-docs").permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()

                .antMatchers("/test/token").permitAll()

                .antMatchers("/homes/**").hasAnyRole("ROLE1")
                .antMatchers("/photo/**").hasAnyRole("ROLE2")
                .antMatchers("/video/**").hasAnyRole("ROLE3")
                //其他的请求都必须要有权限认证
                .anyRequest().authenticated()
//                .and()
//                .logout().permitAll()//定义logout不需要验证
//                .logoutRequestMatcher(new AntPathRequestMatcher("/exit", "GET"))
//                .clearAuthentication(true)//清除认证信息
//                .invalidateHttpSession(true)//使session失效
//                .logoutSuccessHandler(new CustomLogoutSuccessHandler())
//                .and()
//                .exceptionHandling()
//                .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
//                .accessDeniedHandler(customAccessDeniedHandler)
               // .and()
                //开启cookie保存用户数据
//                .rememberMe()
//                .rememberMeParameter("always-remember")
//                .tokenRepository(loginPersistenceService)
                .and().addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
        ;

        // 设置执行其他工作前的 filter （最重要的验证 JWT）
        //用重写的Filter替换掉原有的UsernamePasswordAuthenticationFilter实现使用json 数据也可以登陆
        //http.addFilterAt(customAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class);
        //http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); // JWT Filter

    }

}
